package com.tengju.data.infrastructure.repository;

import com.google.common.collect.Lists;
import com.tengju.data.domain.model.report.AchievementBonus;
import com.tengju.data.domain.model.report.AchievementBonusRiskRepository;
import com.tengju.data.infrastructure.persistence.mybatis.dataobject.AchievementBonusDO;
import com.tengju.data.infrastructure.persistence.mybatis.mapper.tengju.custom.AchievementBonusRiskCustomMapper;
import com.tengju.data.infrastructure.repository.convert.AchievementBonusConvert;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenhang
 * @Date 2021/8/4
 */
@Repository
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class AchievementBonusRiskRepositoryImpl implements AchievementBonusRiskRepository {

    private final AchievementBonusRiskCustomMapper achievementBonusRiskCustomMapper;

    private static final Integer INSERT_BATCH_LIMIT = 200;

    @Override
    public void saveAchievementBonusRisk(List<AchievementBonus> allAchievementBonusList) {
        if (CollectionUtils.isEmpty(allAchievementBonusList)) {
            return;
        }
        List<List<AchievementBonus>> partition = Lists.partition(allAchievementBonusList, INSERT_BATCH_LIMIT);
        for (List<AchievementBonus> achievementBonusList : partition) {
            List<AchievementBonusDO> achievementBonusDOList = achievementBonusList.stream()
                    .map(AchievementBonusConvert::convertAchievementBonusToDO)
                    .collect(Collectors.toList());
            achievementBonusRiskCustomMapper.batchReplaceInsert(achievementBonusDOList);
        }
    }

    @Override
    public int getMaxVersion() {
        return achievementBonusRiskCustomMapper.getMaxVersion();
    }

    @Override
    public void deleteInvalidData(Integer month, Integer version) {
        achievementBonusRiskCustomMapper.deleteInvalidData(month, version);
    }
}
